import React, {useCallback, useEffect, useRef, useState} from "react";
import Head from "./Components/Head";
import {getChannelList} from "../../../../api/channel";
import echarts from 'echarts'
import {getAbnormal} from "../../../../api/statistic";
import moment from "moment";

const alarmNames = ['不匹配异常数', '采集器信号中断异常数', '预期异常数']

function Abnormal({channelType}) {
	const cnType = channelType === 'audio' ? '广播' : '电视'
	const [channelList, setChannelList] = useState([])
	const [channelId, setChannelId] = useState('')
	const [abnormal, setAbnormal] = useState({
		[alarmNames[0]]: 0,
		[alarmNames[1]]: 0,
		[alarmNames[2]]: 0
	})

	const chartRef = useRef(null)
	const [times, setTimes] = useState(
		() => {
			const range = []
			const start = moment().subtract(1, 'month')
			const end = moment()
			range[0] = start
			range[1] = end
			return range
		}
	)


	const chartWrapperWidth = 500,
		chartWrapperHeight = 300,
		seriesSize = chartWrapperWidth / 2,
		seriesTop = (chartWrapperHeight - seriesSize) / 2,
		legendLeft = seriesSize, legendHeight = seriesSize * .6

	function renderChart() {
		console.log('renderChart');
		let chartInstance = null
		const renderedInstance = echarts.getInstanceByDom(chartRef.current)
		if (renderedInstance) {
			chartInstance = renderedInstance
		} else {
			chartInstance = echarts.init(chartRef.current)
		}
		const option = {
			title: {
				left: seriesSize / 2 - 10,
				top: seriesSize / 2 + 10,
				text: `{a|${cnType}异常总数\n${abnormal.total_count}}`,
				textAlign: 'center',
				textStyle: {
					rich: {
						a: {
							// align: 'center',
							fontSize: 16
						},
					}
				}
			},
			tooltip: {
				trigger: 'item',
				formatter: '{a} <br/>{b}: {c} ({d}%)'
			},
			legend: {
				height: legendHeight,
				orient: 'vertical',
				left: legendLeft,
				top: 90,
				data: [alarmNames[0], alarmNames[1], alarmNames[2]],
				formatter: (name) => {
					// console.log(1, name);
					return name + " " + `{a|${abnormal[name]}}`
				},
				textStyle: {
					rich: {
						a: {
							color: 'red',
							lineHeight: 10
						}
					}
				}
			},
			series: [
				{
					height: seriesSize,
					width: seriesSize,
					top: seriesTop,
					name: `${cnType}异常统计`,
					type: 'pie',
					radius: ['50%', '70%'],
					avoidLabelOverlap: false,
					label: {
						show: false,
						position: 'center'
					},
					emphasis: {
						label: {
							show: false,
							fontSize: '30',
							fontWeight: 'bold'
						}
					},
					labelLine: {
						show: false
					},
					data: [
						{value: abnormal.not_match_count, name: alarmNames[0]},
						{value: abnormal.collector_break_count, name: alarmNames[1]},
						{value: abnormal.normal_count, name: alarmNames[2]}
					],
					itemStyle: {
						normal: {
							color: function (params) {
								//自定义颜色
								const colorList = [
									'#3ba1ff', '#4fcb74', '#fbd438'
								];
								return colorList[params.dataIndex]
							}
						}
					}
				}
			]
		};
		chartInstance.setOption(option, true)
	}

	function formatNum(total, num) {
		// console.log(total, num);

		let res = ((num / (total > 0 ? total : 1)) * 100).toFixed(2)
		res = res === "NaN" ? 0 : res
		return res
	}

	useEffect(() => {
		getChannelList({pageSize: 1000, channel_type: channelType}).then(res => {
			setChannelList(res.results)
		})
	}, [])

	useEffect(() => {
		getAbnormal({
			start: times[0].format(),
			end: times[1].format(),
			channel: channelId,
			channel_type: channelType
		}).then(res => {
			setAbnormal({
				...res,
				[alarmNames[0]]: `${res.not_match_count} | ${formatNum(res.total_count, res.distortion_count)} %`,
				[alarmNames[1]]: `${res.collector_break_count} | ${formatNum(res.total_count, res.collector_break_count)} %`,
				[alarmNames[2]]: `${res.normal_count} | ${formatNum(res.total_count, res.normal_count)} %`
			})
		})
	}, [channelId, times])

	useEffect(renderChart, [abnormal])

	const onChannelChange = useCallback((value, options) => {
		setChannelId(value)
	}, [])

	const onDatePickChange = useCallback((moments, values) => {
		setTimes(moments)
	}, [])

	return (
		<>
			<h3 style={{
				borderBottom: '1px solid #aaa',
				paddingBottom: '20px',
				marginBottom: '20px',
				verticalAlign: 'middle'
			}}>{cnType}异常统计
			</h3>
			<Head
				title={`${cnType}节目`}
				times={times}
				channelList={channelList}
				onChannelChange={onChannelChange}
				onDatePickerChange={onDatePickChange}
			/>
			<div ref={chartRef}
			     style={{width: `${chartWrapperWidth}px`, height: `${chartWrapperHeight}px`}}/>
		</>
	)
}

export default Abnormal
